﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace GameViewModel
{
    public class XmlSerializationHelper
    {
        public static void Serialize<T>(string filename, T obj, Action<Exception> onError = null)
        {
            try
            {
                var xs = new XmlSerializer(typeof(T));
                using (var wr = new StreamWriter(filename))
                {
                    xs.Serialize(wr, obj);
                }
            }
            catch (Exception e)
            {
                if (onError != null)
                    onError(e);
            }
        }

        public static T Deserialize<T>(string filename, Action<Exception> onError = null)
        {
            try
            {
                var xs = new XmlSerializer(typeof(T));
                using (var rd = new StreamReader(filename))
                {
                    return (T)xs.Deserialize(rd);
                }
            }
            catch (Exception e)
            {
                if (onError != null)
                    onError(e);
                return default(T);
            }
        }
    }
}